<template>
  <div class="container">
    <div class="login">
      <h1>登录&注册</h1>
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="login-form"
        :size="'large'"
      >
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="form.password"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片验证码" prop="code">
          <template #default>
            <div class="code-wrap">
              <el-input
                v-model="form.code"
                placeholder="请输入图片验证码"
                @keyup.enter.native="login"
              ></el-input>
              <div
                v-html="codeImg"
                id="codeImg"
                class="code-img"
                alt="验证码"
                @click="refreshCode"
                style="margin-left: 10px; cursor: pointer"
              >
            </div>
            </div>
          </template>
        </el-form-item>
        <el-form-item>
          <template #default>
            <div class="remember">
              <el-checkbox v-model="form.remember">记住我</el-checkbox>
              <el-button
                type="primary"
                link
                @click="resetForm"
                >忘记密码?</el-button
              >
            </div>
          </template>
        </el-form-item>
        <el-form-item label-width="0">
          <template #default>
            <div class="btn-wrap">
              <el-button
                type="primary"
                @click="login"
                size="large"
                :loading="loading"
              >
                <template #loading>
                  <div class="custom-loading">
                    <svg class="circular" viewBox="-10, -10, 50, 50">
                      <path
                        class="path"
                        :d="` M 30 15 L 28 17 M 25.61 25.61 A 15 15, 0, 0, 1, 15 30 A 15 15, 0, 1, 1, 27.99 7.5 L 15 15`"
                        style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"
                      />
                    </svg>
                  </div>
                </template>
                <span v-if="text === '登录'">登录</span>
              </el-button>
              <el-button type="success" @click="register" size="large"
                >注册</el-button
              >
            </div>
          </template>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from "element-plus";
import { onMounted, ref } from "vue";
import { getImgCode, userLogin, userRegister } from "@/api/user";
import SHA256 from "@/utils/SHA256";
import router from "@/route";
import User from "@/utils/user";

const userUtils = User.instance

const loading = ref(false);
onMounted(() => {
  form.value = JSON.parse(localStorage.getItem("save-user") || "{}");
  refreshCode()
});

let text = ref("登录");

// 表单实例
const formRef = ref<FormInstance | null>(null);

interface Form {
  account: string;
  password: string;
  remember: boolean;
  code?: string;
}

// 表单数据
const form = ref<Form>({
  account: "",
  password: "",
  remember: false,
  code: "",
});

const code = ref("");

const codeImg = ref("");
/**
 * 获取验证码
 */
const refreshCode = () => {
  getImgCode().then((res: any) => {
    // console.log(res.data);
    // let codeBox = document.getElementById("codeImg") as HTMLImageElement;
    // codeBox.innerHTML = res.data.data;
    codeImg.value = res.data.data;
    code.value = res.data.text.toLowerCase();
  });
};

/**
 * 登录
 */
const login =async () => {
  if (!formRef.value || loading.value) return;
  // TODO: 验证表单
  let valid = await formRef.value.validate();
  if (!valid) return ElMessage.error("验证失败，请检查输入是否正确");
  let params = {
    account: form.value.account,
    password: SHA256(form.value.password),
  };

  loading.value = true;
  // TODO: 登录接口
  userLogin(params)
    .then((res: any) => {
      loading.value = false;
      if (res.code === 200) {
        ElMessage.success("登录成功");
        // TODO: 登录成功逻辑
        // 保存用户信息
        userUtils.saveUserInfo(res.data);
        // TODO: 记住密码逻辑
        if (form.value.remember) {
          delete form.value.code;
          localStorage["save-user"] = JSON.stringify(form.value);
        } else {
          // TODO: 取消记住密码逻辑
          localStorage.removeItem("save-user");
        }
        //跳转到首页
        router.replace("/chat");
      } else {
        ElMessage.warning(res.msg);
      }
    })
    .catch(() => {
      ElMessage.error("请检查网络设置");
    });
};

const resetForm = () => {
  // TODO: 忘记密码逻辑
  ElMessage.info("忘记密码还没有做哦~");
  // form.value = {
  //   account: "",
  //   password: "",
  //   remember: false,
  // };
};

const register = () => {
  // TODO: 注册逻辑
  // ElMessage.info("注册还没有做哦~");
  let params = {
    account: form.value.account,
    password: SHA256(form.value.password),
  };
  // TODO: 注册接口
  userRegister(params).then((res: any) => {
    if (res.code !== 200) {
      ElMessage.error(res.msg);
      return;
    }
    ElMessage.success(res.msg);
    // TODO: 注册成功逻辑
    router.replace("/chat");
  });
};
// 验证码验证规则
const codeRules = (rule:any,value:string ) => {
  if (!rule||!value) return false
  return value.toLocaleLowerCase() === code.value
}
// 表单验证规则
const rules = {
  account: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" },
  ],
  code: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    // { min: 4, max: 4, message: "验证码长度为 4", trigger: "blur" },
    { validator: codeRules, message: "验证码错误", trigger: "blur" },
  ],
};


</script>

<style scoped lang="scss">
.container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(to bottom right, #4facfe, #ff9850, #00f2fe)
    no-repeat;
  background-size: 500% 500%;
  animation: loading 30s ease infinite;
  .login {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 450px;
    width: 600px;
    background-color: #ffffffcc;
    border-radius: 10px;
    padding: 0 40px;
    box-shadow: 0 0 10px #999;

    h1 {
      color: #666;
    }

    .login-form {
      width: 100%;
      .remember {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
      }
      .code-wrap {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .el-input {
          width: 150px;
        }
        .code-img {
          width: 8rem;
          height: 40px;
          cursor: pointer;
          svg{
            width: 100%;
            height: 40px;
          }
        }
      }

      .btn-wrap {
        width: 100%;
        display: flex;
        justify-content: space-evenly;
      }
    }
  }
}

/*登录按钮*/
.el-button .custom-loading .circular {
  margin-right: 6px;
  width: 18px;
  height: 18px;
  animation: loading-rotate 2s linear infinite;
}
.el-button .custom-loading .circular .path {
  animation: loading-dash 1.5s ease-in-out infinite;
  stroke-dasharray: 90, 150;
  stroke-dashoffset: 0;
  stroke-width: 2;
  stroke: var(--el-button-text-color);
  stroke-linecap: round;
}

@keyframes loading {
  0% {
    background-position: 0% 0%;
  }
  50% {
    background-position: 100% 100%;
  }
  100% {
    background-position: 0% 0%;
  }
}
</style>
